#include<iostream>
#include<string>
#include<fstream>
#include"node.h"
using namespace std;
const char * file="/home/pi/code/al/ali.csv";
const char * sfile="/home/pi/code/al/nali.csv";
ifstream fin;
ofstream fout;
bool getitem(string temp[]);
int main()
{
    fin.open(file);
    string temp[4];
    node *hnode=new node;
    node *cnode=NULL;
    node *enode=NULL;
    if(!getitem(temp))
    {
	temp[0]="-1";
	hnode->set(temp,NULL);
	cnode=hnode;
    }
    if(!getitem(temp))
    {
	enode=new node;
	enode->set(temp,NULL);
	hnode->next=enode;
	cnode=enode;
    }
    while(!getitem(temp))
    {
	if(temp[0]==cnode->ali[0])
	{
	    enode=new node;
	    enode->set(temp,NULL);
	    cnode->next=enode;
	    cnode=enode;
	    enode->next=NULL;
	}
	else 
	{
	    enode=new node;
	    enode->set(temp,NULL);
	    cnode->next=enode;
	    cnode=enode;
	    enode->next=NULL;
	    break;
	}
    }

    fout.open(sfile,ios_base::out|ios_base::app);
    int t=1;
    node *tnode=NULL;						//商品工作结点	
    node *thnode=hnode->next;					//商品头结点
    node *twnode=NULL;
    bool ifcount=0;
    bool ifend=0;
    for(cnode=thnode;cnode;cnode=cnode->next){
	if(ifend==0&&cnode->ali[0]==enode->ali[0])
	{
	    for(cnode=thnode;cnode&&cnode!=enode;)		//删除已读结点
	    {	
		twnode=cnode;
		cnode=cnode->next;
		delete twnode;
	    }
	    thnode=enode;
	    while(true)
	    {
		ifend=getitem(temp);
		if(ifend==0)
		{
		    if(temp[0]==cnode->ali[0])
		    {
			enode=new node;
			enode->set(temp,NULL);
			cnode->next=enode;
			cnode=enode;
			enode->next=NULL;
		    }
		    else 
		    {
			enode=new node;
			enode->set(temp,NULL);
			cnode->next=enode;
			enode->next=NULL;
			cnode=thnode;
			break;
		    }
		}
		else
		{
		    cnode=thnode;
		    break;
		}
	    }
	}
	ifcount=0;
	if(cnode->ali[1]!=thnode->ali[1])			//新的品牌
	    thnode=cnode;
	for(twnode=thnode;twnode!=cnode;twnode=twnode->next)
	    if(twnode->ali[1]==cnode->ali[1]&&twnode->ali[2]==cnode->ali[2]&&twnode->ali[3]==cnode->ali[3])
	    {
		ifcount=1;
		break;
	    }
	if(ifcount==1)						//已经输出的条目
	    continue;
	tnode=cnode->next;
	while(tnode&&(tnode->ali[1]==cnode->ali[1]))		       //输出
	{
	    if(tnode->ali[2]==cnode->ali[2]&&tnode->ali[3]==cnode->ali[3])
		t++;
	    tnode=tnode->next;
	}
	fout<<cnode->ali[0]<<"\t"<<cnode->ali[1]<<"\t"<<cnode->ali[2]<<"\t"<<cnode->ali[3]<<"\t"<<t<<endl;

	t=1;
    }
    if(hnode)
	delete hnode;
    fin.close();

}
bool getitem(string temp[])
{
    if(fin.is_open()&&!fin.eof()){
	for(int i=0;i<4;i++)
	    fin>>temp[i];
	return 0;
    }
    else 
	return 1;
}
